import { PlusOutlined } from '@ant-design/icons';
import React, { useState, useEffect, useRef, useContext } from 'react';
import {
    Button, Space, Col, Drawer, Form, Input, Row, Select, message
} from 'antd';
import './index.css';
import axios from 'axios';
import { AuthContext } from '../../contexts/AuthContext';
import { useTranslation } from 'react-i18next';

const CreateBugs = ({ onCreateSuccess }) => {
    const [open, setOpen] = useState(false);
    const showDrawer = () => {
        setOpen(true);
    };
    const onClose = () => {
        setOpen(false);
    };
    const [inputVisible, setInputVisible] = useState(false);
    const [editInputValue, setEditInputValue] = useState('');
    const inputRef = useRef(null);
    const { token } = useContext(AuthContext);
    const { t } = useTranslation();
    const editInputRef = useRef(null);
    const { Option } = Select;

    useEffect(() => {
        if (inputVisible) {
            inputRef.current?.focus();
        }
    }, [inputVisible]);

    useEffect(() => {
        editInputRef.current?.focus();
    }, [editInputValue]);

    const options = [
        {
            value: 'critical',
            label: t('critical'),
        },
        {
            value: 'high',
            label: t('high'),
        },
        {
            value: 'medium',
            label: t('medium'),
        },
        {
            value: 'low',
            label: t('low'),
        },
        {
            value: 'negligible',
            label: t('negligible'),
        },
        {
            value: 'unknown',
            label: t('unknown'),
        },
    ];

    const [form] = Form.useForm();

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();

            const data = {
                assigner: [values.assigner],
                description: values.description,
                id: values.id,
                severities: [
                    {
                        rank: values.severityRank === 'critical' ? 5 :
                            values.severityRank === 'high' ? 4 :
                                values.severityRank === 'medium' ? 3 :
                                    values.severityRank === 'low' ? 2 :
                                        values.severityRank === 'negligible' ? 1 : 0,
                        scheme: values.severityScheme,
                        source: values.severitySource,
                        value: {
                            vector: values.severityVector,
                            version: values.severityVersion
                        },
                        rankLabel: values.severityRank
                    }
                ]
            };

            const response = await axios.post('/api/v1/vulnerability/create', data, {
                headers: {
                    'Authorization': token,
                }
            });

            if (response.data.code === 0) {
                console.log(response.data);
                message.success(t('成功'));
                setOpen(false);
                form.resetFields();
                if (onCreateSuccess) {
                    onCreateSuccess();
                }
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            } else {
                message.error(t('失败'));
            }
        } catch (error) {
            console.error(t('表单验证或请求出错:'), error);
            message.error(t('表单验证或请求出错'));
        }
    };

    return (
        <>
            <Button className='create-project-button' type="primary" style={{width:"190px"}}
             onClick={showDrawer} icon={<PlusOutlined />}>
                {t('创建漏洞')}
            </Button>
            <Drawer
                title={t('创建漏洞')}
                width={720}
                onClose={onClose}
                open={open}
                style={{
                    body: {
                        paddingBottom: 80,
                    },
                }}
                extra={
                    <Space>
                        <Button onClick={onClose}>{t('取消')}</Button>
                        <Button onClick={handleSubmit} type="primary">
                            {t('提交')}
                        </Button>
                    </Space>
                }
            >
                <Form layout="vertical" form={form}>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="id"
                                label={t('漏洞编号')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入漏洞编号'),
                                    },
                                ]}
                            >
                                <Input placeholder={t('请输入漏洞编号')} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="assigner"
                                label={t('提供者')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入提供者'),
                                    },
                                ]}
                            >
                                <Input placeholder={t('请输入提供者')} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '10px' }}>
                        <Col span={12}>
                            <Form.Item
                                name="severityRank"
                                label={t('严重程度')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请选择严重程度'),
                                    },
                                ]}
                            >
                                <Select placeholder={t('请选择严重程度')} options={options} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="severityScheme"
                                label={t('严重程度方案')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入严重程度方案'),
                                    },
                                ]}
                            >
                                <Input placeholder={t('请输入严重程度方案')} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '10px' }}>
                        <Col span={12}>
                            <Form.Item
                                name="severitySource"
                                label={t('严重程度来源')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入严重程度来源'),
                                    },
                                ]}
                            >
                                <Input placeholder={t('请输入严重程度来源')} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="severityVector"
                                label={t('严重程度向量')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入严重程度向量'),
                                    },
                                ]}
                            >
                                <Input placeholder={t('请输入严重程度向量')} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '10px' }}>
                        <Col span={12}>
                            <Form.Item
                                name="severityVersion"
                                label={t('严重程度版本')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入严重程度版本'),
                                    },
                                ]}
                            >
                                <Input placeholder={t('请输入严重程度版本')} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '10px' }}>
                        <Col span={24}>
                            <Form.Item
                                name="description"
                                label={t('描述')}
                                rules={[
                                    {
                                        required: true,
                                        message: t('请输入描述'),
                                    },
                                ]}
                            >
                                <Input.TextArea rows={4} placeholder={t('请输入描述')} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Drawer>
        </>
    );
};

export default CreateBugs;